<?php

require_once '../config.php';
require_once '../autoloader.php';

$files = scandir(__DIR__ . "/patches", SCANDIR_SORT_ASCENDING);
if (is_array($files)) {

    $patches = array();
    foreach ($files as $file) {
        $tmpSplit = explode("_", $file);
        if (is_array($tmpSplit)) {
            if (is_numeric($tmpSplit[0]) && $tmpSplit[0] > 0) {
                $patches['patch' . $tmpSplit[0]] = $file;
            }
        }
    }

    $db = new db();
    $db_version = $db->getFirst("MAX(`patch`) as `version`", "db_version");
    if (is_array($db_version)) {
        $next_patch = $db_version['version'] + 1;
        $not_founds = 0;
        while ($not_founds < 10) {
            $key = 'patch' . $next_patch;
            if (isset($patches[$key])) {
                $file = __DIR__ . "/patches/" . $patches[$key];
                if (file_exists($file)) {
                    $sql = file_get_contents($file);
                    if ($db->sqlexec($sql)){
                         $debug = $db->sqlexec("INSERT INTO `db_version`(`patch`,`sql`) VALUES (".$next_patch.",'".$db->escapestring($sql)."')");
                         if (!$debug){
                             die("FEJL: i update db_version til ".$next_patch);
                         }else{
                             echo "<b>PATCH ".$next_patch.":</b> ".$sql."<hr>";
                         }
                    }else{
                        echo "FEJL i patch<hr>";
                        echo $sql;
                        echo "<hr>PATCH: ";
                        echo $next_patch;
                        die();
                    }
                }
            } else {
                $not_founds++;
            }
            $next_patch++;
        }
    }
}